//
//  SMAFNetworkManager.m
//  NetwrokDemo
//
//  Created by Ted Liu on 16/5/4.
//  Copyright © 2016年 Ted Liu. All rights reserved.
//

#import "SMAFNetworkManager.h"
#import "SMAFNetworkHandler.h"
#import "SMAFNetworkUpParam.h"
#import "SMAFNetworkSessionManager.h"
@implementation SMAFNetworkManager
/// 返回单例
static SMAFNetworkManager *_manager = nil;
+ (instancetype) sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[SMAFNetworkManager alloc ]init];
    });
    return _manager;
}

#pragma mark - GET 请求的回调方法

/**
 *   GET请求的公共方法 以下方法都调用这个方法 根据传入的不同参数觉得回调的方式
 *
 *   @param url           ur
 *   @param paramsDict   paramsDict
 *   @param target       target
 *   @param action       action
 *   @param delegate     delegate
 *   @param successBlock successBlock
 *   @param failureBlock failureBlock
 *   @param showHUD      showHUD
 */
+ (void)getRequstWithURL:(NSString*)url
                  params:(NSDictionary*)params
               requestId:(NSString*)requestId
              serverTyep:(SMNetServer)serverType
                  action:(SEL)action
                delegate:(id)delegate
            successBlock:(SMAFSuccessBlock)successBlock
            failureBlock:(SMAFFailureBlock)failureBlock
                 showHUD:(BOOL)showHUD
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:params];
    [[SMAFNetworkHandler sharedInstance] requestURL:url networkType:SMAFNetWorkGET params:mutableDict requestId:requestId serverType:serverType  delegate:delegate showHUD:showHUD successBlock:successBlock failureBlock:failureBlock];
}
/**
 *   GET请求通过Block 回调结果
 *
 *   @param url          url
 *   @param paramsDict   paramsDict
 *   @param successBlock  成功的回调
 *   @param failureBlock  失败的回调
 *   @param showHUD      是否加载进度指示器
 */
+ (void)getRequstWithURL:(NSString*)url
                  params:(NSDictionary*)params
               requestId:(NSString *)requestId
              serverType:(SMNetServer)server
            successBlock:(SMAFSuccessBlock)successBlock
            failureBlock:(SMAFFailureBlock)failureBlock
                 showHUD:(BOOL)showHUD
{
    [SMAFNetworkManager getRequstWithURL:url params:params requestId:requestId serverTyep:server action:nil delegate:nil successBlock:successBlock failureBlock:failureBlock showHUD:showHUD];
}
/**
 *   GET请求通过代理回调
 *
 *   @param url         url
 *   @param paramsDict  请求的参数
 *   @param delegate    delegate
 *   @param showHUD    是否转圈圈
 */
+ (void)getRequstWithURL:(NSString*)url
                  params:(NSDictionary*)params
               requestId:(NSString *)requestId
              serverType:(SMNetServer)server
                delegate:(id<SMAFNetworkDelegate>)delegate
                 showHUD:(BOOL)showHUD
{
    [SMAFNetworkManager getRequstWithURL:url params:params requestId:requestId serverTyep:server action:nil delegate:delegate successBlock:nil failureBlock:nil showHUD:showHUD];
}

#pragma mark - POST请求的回调方法
/**
 *   发送一个 POST请求的公共方法 传入不同的回调参数决定回调的方式
 *
 *   @param url           ur
 *   @param paramsDict   paramsDict
 *   @param target       target
 *   @param action       action
 *   @param delegate     delegate
 *   @param successBlock successBlock
 *   @param failureBlock failureBlock
 *   @param showHUD      showHUD
 */
+ (void)postReqeustWithURL:(NSString*)url
                    params:(NSDictionary*)params
                 requestId:(NSString *)requestId
                serverType:(SMNetServer)server
                    target:(id)target
                    action:(SEL)action
                  delegate:(id<SMAFNetworkDelegate>)delegate
              successBlock:(SMAFSuccessBlock)successBlock
              failureBlock:(SMAFFailureBlock)failureBlock
                   showHUD:(BOOL)showHUD
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:params];
    
    [[SMAFNetworkHandler sharedInstance] requestURL:url networkType:SMAFNetWorkPOST params:mutableDict requestId:requestId serverType:server delegate:delegate showHUD:showHUD successBlock:successBlock failureBlock:failureBlock];
}
/**
 *   通过 Block回调结果
 *
 *   @param url           url
 *   @param paramsDict    请求的参数字典
 *   @param successBlock  成功的回调
 *   @param failureBlock  失败的回调
 *   @param showHUD       是否加载进度指示器
 */
+ (void)postReqeustWithURL:(NSString*)url
                    params:(NSDictionary*)params
                 requestId:(NSString *)requestId
                serverType:(SMNetServer)server
              successBlock:(SMAFSuccessBlock)successBlock
              failureBlock:(SMAFFailureBlock)failureBlock
                   showHUD:(BOOL)showHUD
{
    [SMAFNetworkManager postReqeustWithURL:url params:params requestId:requestId serverType:server target:nil action:nil delegate:nil successBlock:successBlock failureBlock:failureBlock showHUD:showHUD];
}
/**
 *   post请求通过代理回调
 *
 *   @param url         url
 *   @param paramsDict  请求的参数
 *   @param delegate    delegate
 *   @param showHUD    是否转圈圈
 */
+ (void)postReqeustWithURL:(NSString*)url
                    params:(NSDictionary*)params
                 requestId:(NSString *)requestId
                serverType:(SMNetServer)server
                  delegate:(id<SMAFNetworkDelegate>)delegate
                   showHUD:(BOOL)showHUD;
{
    [SMAFNetworkManager postReqeustWithURL:url params:params requestId:requestId serverType:server target:nil action:nil delegate:delegate successBlock:nil failureBlock:nil showHUD:showHUD];
}
#pragma mark - PATCH请求的回调方法
/**
 *   发送一个 PATCH请求的公共方法 传入不同的回调参数决定回调的方式
 *
 *   @param url           ur
 *   @param paramsDict   paramsDict
 *   @param target       target
 *   @param action       action
 *   @param delegate     delegate
 *   @param successBlock successBlock
 *   @param failureBlock failureBlock
 *   @param showHUD      showHUD
 */
+ (void)patchReqeustWithURL:(NSString*)url
                     params:(NSDictionary*)params
                  requestId:(NSString *)requestId
                 serverType:(SMNetServer)server
                     target:(id)target
                     action:(SEL)action
                   delegate:(id<SMAFNetworkDelegate>)delegate
               successBlock:(SMAFSuccessBlock)successBlock
               failureBlock:(SMAFFailureBlock)failureBlock
                    showHUD:(BOOL)showHUD
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary:params];
    
    [[SMAFNetworkHandler sharedInstance] requestURL:url networkType:SMAFNetWorkPATCH params:mutableDict requestId:requestId serverType:server delegate:delegate showHUD:showHUD successBlock:successBlock failureBlock:failureBlock];
}
/**
 *   通过 Block回调结果
 *
 *   @param url           url
 *   @param paramsDict    请求的参数字典
 *   @param successBlock  成功的回调
 *   @param failureBlock  失败的回调
 *   @param showHUD       是否加载进度指示器
 */
+ (void)patchReqeustWithURL:(NSString*)url
                     params:(NSDictionary*)params
                  requestId:(NSString *)requestId
                 serverType:(SMNetServer)server
               successBlock:(SMAFSuccessBlock)successBlock
               failureBlock:(SMAFFailureBlock)failureBlock
                    showHUD:(BOOL)showHUD
{
    [SMAFNetworkManager patchReqeustWithURL:url params:params requestId:requestId serverType:server  target:nil action:nil delegate:nil successBlock:successBlock failureBlock:false showHUD:YES];
}
/**
 *   post请求通过代理回调
 *
 *   @param url         url
 *   @param paramsDict  请求的参数
 *   @param delegate    delegate
 *   @param showHUD    是否转圈圈
 */
+ (void)patchReqeustWithURL:(NSString*)url
                     params:(NSDictionary*)params
                  requestId:(NSString *)requestId
                 serverType:(SMNetServer)server
                   delegate:(id<SMAFNetworkDelegate>)delegate
                    showHUD:(BOOL)showHUD;
{
    [SMAFNetworkManager patchReqeustWithURL:url params:params requestId:requestId serverType:server target:nil action:nil delegate:delegate successBlock:nil failureBlock:nil showHUD:showHUD];
}

/**
 *  上传文件
 *
 *  @param url          上传文件的 url 地址
 *  @param paramsDict   参数字典
 *  @param successBlock 成功
 *  @param failureBlock 失败
 *  @param showHUD      显示 HUD
 */
+ (void)uploadFileWithURL:(NSString*)url
                   params:(NSDictionary*)paramsDict
                requestId:(NSString *) requestId
               serverType:(SMNetServer) server
             successBlock:(SMAFSuccessBlock)successBlock
             failureBlock:(SMAFFailureBlock)failureBlock
              uploadParam:(SMAFNetworkUpParam *)uploadParam
                  showHUD:(BOOL)showHUD{
    
    AFHTTPSessionManager *manager = [SMAFNetworkSessionManager sharedInstance].sessionManager_def;
    // 显示进度
    if (showHUD) {
        [MBProgressHUD showActiveMessageNew:@"上传中" withBackground:YES];
    }
    [manager POST:url parameters:paramsDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        if (uploadParam.picDataArray.count > 0)
        {
            NSObject *firstObj = [uploadParam.picDataArray objectAtIndex:0];
            if ([firstObj isKindOfClass:[UIImage class]])
            {// 图片
                for(NSInteger i = 0; i < uploadParam.picDataArray.count; i++)
                {
                    UIImage *eachImg = [uploadParam.picDataArray objectAtIndex:i];
                    //NSData *eachImgData = UIImagePNGRepresentation(eachImg);
                    NSData *eachImgData = UIImageJPEGRepresentation(eachImg, 0.5);
                    [formData appendPartWithFileData:eachImgData name:[NSString stringWithFormat:@"img%ld", i+1] fileName:[NSString stringWithFormat:@"img%ld.jpg", i+1] mimeType:@"image/jpeg"];
                }
            }else
            {// 视频
                NSObject *firstObj = [uploadParam.videoDataArray objectAtIndex:0];
                if (firstObj != nil)
                {
                    for (int i = 0 ; i < uploadParam.videoDataArray.count; i ++) {
                        
                        //                        ALAsset *asset = [uploadParam.videoDataArray objectAtIndexSafe:i];
                        
                        // 获取沙盒目录
                        NSString *videoPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"video%d.mov",i]];
                        NSURL *url = [NSURL fileURLWithPath:videoPath];
                        NSError *theErro = nil;
                        /**
                         *  有问题 还没有实现方法
                         */
                        //                        BOOL exportResult = [asset exportDataToURL:url error:&theErro];
                        
                        NSData *videoData = [NSData dataWithContentsOfURL:url];
                        [formData appendPartWithFileData:videoData name:[NSString stringWithFormat:@"video%i",i] fileName:videoPath mimeType:@"video/quicktime"];
                        
                    }
                }
            }
        }
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [MBProgressHUD dismissHUD];
        
        SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
        
        response.resultDic = responseObject;
        response.resultCode = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
        ITTDPRINT(@"\n\n----请求的返回结果 %@\n",responseObject);
        if (successBlock) {
            successBlock(task,response);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [MBProgressHUD dismissHUD];
        SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
        
        if (error.userInfo[@"NSLocalizedDescription"] == NULL)
        {
            response.errorMessage = @"";
        } else
        {
            response.errorMessage = error.userInfo[@"NSLocalizedDescription"];
        }
        ITTDPRINT(@"---error==%@\n",error.localizedDescription);
        if (failureBlock) {
            failureBlock(task,response,error);
        }
    }];
}
@end
